package com.corner.utils;

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;

import java.io.IOException;

/**
 * 音乐播放器
 *
 * @author Administrator
 */
public class AudioPlayer {

    private MediaPlayer mediaPlayer;
    private OnCompletionListener listener;
    private String path;
    private OnFinishedCallBack onFinishedCallBack;
    private boolean hasReleased = false;

    public AudioPlayer() {
        mediaPlayer = new MediaPlayer();
        listener = new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                mediaPlayer.stop();
                mediaPlayer.release();
                hasReleased = true;
                finish();
            }
        };
    }

    /**
     * 开始
     *
     * @throws IOException
     * @throws IllegalStateException
     * @throws SecurityException
     * @throws IllegalArgumentException
     */
    public void start(String path, OnFinishedCallBack onFinishedCallBack) throws IllegalArgumentException,
            SecurityException, IllegalStateException, IOException {
        this.onFinishedCallBack = onFinishedCallBack;
        mediaPlayer.setDataSource(path);
        mediaPlayer.prepare();
        mediaPlayer.start();
        this.setPath(path);
        mediaPlayer.setOnCompletionListener(listener);
    }

    public void stop() {
        if (isPlaying()) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
                mediaPlayer.release();
                finish();
            }
            hasReleased = true;
        }
    }

    public boolean isPlaying() {
        if (mediaPlayer != null) {
            return !hasReleased;
        }
        return false;
    }

    /**
     * 结束播放
     */
    private void finish() {
        if (onFinishedCallBack != null) {
            onFinishedCallBack.onFinished(getPath());
        }
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public int getDuration() {
        if (mediaPlayer == null || hasReleased) {
            return 0;
        }
        return mediaPlayer.getDuration();
    }

    public int getCurrPosition() {
        if (mediaPlayer == null || hasReleased) {
            return 0;
        }
        return mediaPlayer.getCurrentPosition();
    }

    /**
     * 播放结束时回调
     *
     * @author Administrator
     */
    public interface OnFinishedCallBack {
        void onFinished(String path);
    }
}
